package com.rew.canteenbox.activities;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.*;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.rew.canteenbox.R;
import com.rew.canteenbox.bases.SlideActivity;
import com.rew.canteenbox.fragments.*;
import com.rew.canteenbox.functions.StatusBarUtils;
import com.rew.canteenbox.models.ExitDialog;

import static com.rew.canteenbox.bases.AppData.ACTIVE;
import static com.rew.canteenbox.bases.AppData.GRAY;

/**
 * 菜单界面（主界面）.
 * <p>
 * Created by HuiWen Ren on 2016/10/15.
 */
public class MainActivity extends SlideActivity
        implements View.OnClickListener,
        NavigationView.OnNavigationItemSelectedListener{

    // 逻辑变量声明.

    //TODO:明确动作判定，添加左右误差，将低灵敏度

        public static int inStyle;  //进入动画.
        public static int outStyle; //退出动画.
        private DrawerLayout drawer;    //布局.

    /**
     *  Activity主体部分.
     *
     *  onCreate(..)                    -活动创建
     *  actionStart(Context context)    -启动接口（context = [MainActivity.this]）
     */

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 设置状态栏颜色
        StatusBarUtils.setWindowStatusBarColor(MainActivity.this, R.color.colorPrimaryDark);

        // 切换动画初始化
        overridePendingTransition(inStyle, outStyle);

        // 布局初始化.
        drawer = (DrawerLayout) findViewById(R.id.main_activity);
        drawer.setOnTouchListener(this);

        // Fragment初始化.
        setDefaultFragment();

        // ToolBar初始化.
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.main_nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        // Bottom初始化
        initView();
        initEvent();

    }

    public static void actionStart(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onResume(){
        super.onResume();
        if(frgMark == 2){
            fMenu = new FMenu();
            freshFragment(R.id.fg_content, fMenu, 2);
        }
    }

    /**
     *  主体布局加载部分.
     *
     *  ActionBar部分.
     *
     *  onCreateOptionsMenu(Menu menu)              -加载选项菜单(…)
     *  onOptionsItemSelected(MenuItem item)        -选项栏目监听(…)
     *  onNavigationItemSelected（MenuItem item)     -导航栏监听(≡)
     */

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            //onBuilding();
            FSetting fSetting = new FSetting();
            freshFragment(R.id.fg_content,fSetting,4);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        switch(id){
            case R.id.nav_camera:
            case R.id.nav_gallery:
            case R.id.nav_manage:
            case R.id.nav_share:
                onBuilding();
                break;
            case R.id.nav_end:
                ExitDialog.exitDialog(MainActivity.this).show();
                break;
            default:
                break;
        }

        drawer.closeDrawer(GravityCompat.START);
        return true;
    }


    /**
     *  BottomBar部分.
     *
     *  initEvent()         -初始化按钮对应关系
     *  initView()          -初始化布局对应关系
     *  restartBotton()     -初始化静止状态（灰）
     *  onClick(View view)  -设置点击监听
     */

    private void initEvent() {
        // 设置按钮监听.
        ll_buy.setOnClickListener(this);
        ll_home.setOnClickListener(this);
        ll_friend.setOnClickListener(this);
        ll_setting.setOnClickListener(this);
    }

    private void initView() {

        // 底部菜单4个Linearlayout.
        this.ll_buy = (LinearLayout) findViewById(R.id.ll_buy);
        this.ll_home = (LinearLayout) findViewById(R.id.ll_home);
        this.ll_friend = (LinearLayout) findViewById(R.id.ll_friend);
        this.ll_setting = (LinearLayout) findViewById(R.id.ll_setting);

        // 底部菜单4个ImageView
        this.iv_buy = (ImageView) findViewById(R.id.iv_buy);
        this.iv_home = (ImageView) findViewById(R.id.iv_home);
        this.iv_friend = (ImageView) findViewById(R.id.iv_friend);
        this.iv_setting = (ImageView) findViewById(R.id.iv_setting);

        // 底部菜单4个菜单标题.
        this.tv_buy = (TextView) findViewById(R.id.tv_buy);
        this.tv_home = (TextView) findViewById(R.id.tv_home);
        this.tv_friend = (TextView) findViewById(R.id.tv_friend);
        this.tv_setting = (TextView) findViewById(R.id.tv_setting);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_buy:
                loadFragmentById(1);
                break;
            case R.id.ll_home:
                loadFragmentById(2);
                break;
            case R.id.ll_friend:
                loadFragmentById(3);
                break;
            case R.id.ll_setting:
                loadFragmentById(4);
                break;

            default:
                break;
        }
    }

    private void restartBotton() {
        iv_buy.setImageResource(R.drawable.button_default);
        iv_home.setImageResource(R.drawable.button_default);
        iv_friend.setImageResource(R.drawable.button_default);
        iv_setting.setImageResource(R.drawable.button_default);

        // TextView置为灰色.
        tv_buy.setTextColor(GRAY);
        tv_home.setTextColor(GRAY);
        tv_friend.setTextColor(GRAY);
        tv_setting.setTextColor(GRAY);
    }

    /**
     * Fragment碎片部分.
     *
     *  setDefaultFragment()    -布局初始化  -初始化为FMenu
     *  loadFragmentById(int k) -按照编码加载碎片   k = [1]-FBuy [2]-FMenu [3]-FCircle [4]-FMe
     *  freshFragment(          -刷新布局
     *      int fg_content,     -需要替代的碎片    -默认输入为 fragment_content
     *      Fragment freFg,     -替换部分          -传入待替换实例
     *      int k)              -待换碎片代码      -与当前比较决定切换动画方式
     *  findNextId(int k)       -找到下一个id
     *  findPreId（int k)       -找到上一个id
     */

    // 当前Fragment编码
    private int frgMark;

    // Fragment实例
    private FBuy fBuy;    private FMenu fMenu;
    private FCircle fCircle;    private FMe fMe;

    private FSetting fSetting;

    // 底部菜单4个Linearlayout
    private LinearLayout ll_buy;    private LinearLayout ll_home;
    private LinearLayout ll_friend;    private LinearLayout ll_setting;

    // 底部菜单4个ImageView
    private ImageView iv_buy;    private ImageView iv_home;
    private ImageView iv_friend;    private ImageView iv_setting;

    // 底部菜单4个菜单标题
    private TextView tv_buy;    private TextView tv_home;
    private TextView tv_friend;    private TextView tv_setting;


    private void setDefaultFragment() {
        fMenu = new FMenu();
        frgMark = 2;
        freshFragment(R.id.fg_content, fMenu,2);
        lastSlide = System.currentTimeMillis();
    }

    private void loadFragmentById(int k){
        FragmentManager fm = getFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        // 在每次点击后将所有的底部按钮(ImageView,TextView)颜色改为灰色，然后根据点击着色
        restartBotton();
        // ImageView和TetvView置为蓝色，页面随之跳转.
        switch (k) {
            case 1:
                iv_buy.setImageResource(R.drawable.pressed_default);
                tv_buy.setTextColor(ACTIVE);
                fBuy = new FBuy();
                freshFragment(R.id.fg_content, fBuy,1);
                frgMark = 1;
                break;
            case 2:
                iv_home.setImageResource(R.drawable.pressed_default);
                tv_home.setTextColor(ACTIVE);
                freshFragment(R.id.fg_content, fMenu,2);
                frgMark = 2;
                break;
            case 3:
                iv_friend.setImageResource(R.drawable.pressed_default);
                tv_friend.setTextColor(ACTIVE);
                fCircle = new FCircle();
                freshFragment(R.id.fg_content, fCircle,3);
                frgMark = 3;
                break;
            case 4:
                iv_setting.setImageResource(R.drawable.pressed_default);
                tv_setting.setTextColor(ACTIVE);
                //fMe = new FMe();
                fSetting = new FSetting();
                freshFragment(R.id.fg_content, fSetting,4);
                frgMark = 4;
                break;
            default:
                break;
        }
    }

    private void freshFragment(int fg_content, Fragment freFg, int k){
        FragmentManager fm = getFragmentManager();
        // 开启Fragment事务
        FragmentTransaction transaction = fm.beginTransaction();
        if(k<frgMark){
            transaction.setCustomAnimations(
                    R.anim.fragment_slide_left_in,
                    R.anim.fragment_slide_right_out);
        } else {
            transaction.setCustomAnimations(
                    R.anim.fragment_slide_right_in,
                    R.anim.fragment_slide_left_out);
        }
        transaction.replace(fg_content, freFg);
        //transaction.addToBackStack(null);
        transaction.commit();
    }

    private int findNextId(int k){
        if(k == 4){
            return 1;
        } else {
            return k+1;
        }
    }

    private int findPreId(int k){
        if(k == 1){
            return 4;
        } else {
            return k-1;
        }
    }

    /**
     * 适配性更改部分.
     *
     *   onBackPressed()        -背景点击（super -> 优先关闭侧边栏）
     *   onKeyDown(..)          -回退按钮（super -> 优先关闭侧边栏 & 退出确认）
     *   right()                -向右滑动（None  -> 向左切换Fragment）
     *   left()                 -向左滑动（None  -> 优先关闭侧边栏 & 向右切换Fragment）
     *   dispatchTouchEvent(..) -点击处理（super -> 优先滑动判断）
     */

    // 时间戳
    private long lastSlide;

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                ExitDialog.exitDialog(MainActivity.this).show();
                return true;
            }
            return super.onKeyDown(keyCode, event);
        }
        return true;
    }

    @Override
    public void right() {
        if (System.currentTimeMillis() - lastSlide >= 500
                && frgMark != 1) {
            loadFragmentById(findPreId(frgMark));
        }
        lastSlide = System.currentTimeMillis();
    }

    @Override
    public void left() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            if (System.currentTimeMillis() - lastSlide >= 500
                    && frgMark != 4) {
                loadFragmentById(findNextId(frgMark));
            }
            lastSlide = System.currentTimeMillis();
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        onTouch(drawer, ev);
        return super.dispatchTouchEvent(ev);
    }

    /**
     *  测试函数部分.
     *
     *  onBuilding()       -成功响应
     */
    private void onBuilding(){
        Toast.makeText(MainActivity.this, "功能尚未开放~",
                Toast.LENGTH_SHORT).show();
    }
}

